﻿using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.Editor;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Web;
using EPiServer.Web.PropertyControls;

namespace OpenWaves.EPiServer.VideoProperty
{
    [TemplateDescriptor(TagString = VideoProperty.UIHint)]
    public class PropertyVideoControl : PropertyDataControl, IRenderTemplate<global::EPiServer.Url>, IRenderTemplate
    {
        public override void CreateDefaultControls()
        {
            string url = ToString();
            Control vControl;
            if(PageEditing.PageIsInEditMode)
            {
                LiteralControl ltr = new LiteralControl();
                ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">.video-wrapper { display:inline-block; }</style>";
                this.Page.Header.Controls.Add(ltr);
                vControl = new Video.Web.Controls.VideoThumbnail()
                {
                    VideoUrl = url,
                    Width = GetIntegerValue("VideoWidth", 480),
                    Height = GetIntegerValue("VideoHeight", 320)
                }; 
            }
            else
            {
                vControl = new Video.Web.Controls.Video
                {
                    VideoUrl = url,
                    Width = GetIntegerValue("VideoWidth", 480),
                    Height = GetIntegerValue("VideoHeight", 320)
                };
            }

            


            var videoWrapper = new VideoContainerControl(HtmlTextWriterTag.Div);

            videoWrapper.Controls.Add(vControl);

            this.CopyWebAttributes(videoWrapper);

            if (string.IsNullOrWhiteSpace(videoWrapper.CssClass))
            {
                videoWrapper.CssClass = "video-wrapper";
            }
            else
            {
                videoWrapper.CssClass += " video-wrapper";
            }

            Controls.Add(videoWrapper);
        }

        private int GetIntegerValue(string key, int defaultValue)
        {
            if (!RenderSettings.ContainsKey(key))
            {
                return defaultValue;
            }

            int value;
            if (int.TryParse(RenderSettings[key] as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
            {
                return value;
            }
            return defaultValue;
        }

        /// <summary>
        /// EPiServer check:
        /// !control.GetType().IsSubclassOf(typeof (WebControl))
        /// we need simple class that inherits from WebControl
        /// </summary>
        private class VideoContainerControl : WebControl
        {
            protected VideoContainerControl()
            {
            }

            public VideoContainerControl(HtmlTextWriterTag tag)
                : base(tag)
            {
            }
        }

    }


}